package com.usc.csci588.chaltrojan.login;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.usc.csci588.chaltrojan.R;
import com.usc.csci588.chaltrojan.SetDestinationMapActivity;
import com.usc.csci588.chaltrojan.ui.main.MainUIMapActivity;

import android.view.MotionEvent;

public class CreateNewTripFormActivity extends Activity {

	private TextView destination_tv;
	private TextView name_tv;
	private TextView password_tv;
	private TextView datepkr_tv;
	private String dateString;

	double[] ll;
	Double lat;
	Double lon;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_new_trip_form_layout);
		Button SubmitButton = (Button) findViewById(R.id.new_trip_submit_button);
		
		dateString = "";
		
//		Intent i = new Intent(getApplicationContext(), MainUIMapActivity.class);
//		Bundle sendInfo = new Bundle();
//		sendInfo.putInt(Constants.mainUIRequestedFrom, Constants.mainUIFromCreateTrip);		
//		i.putExtra(Constants.mainUIFromCreateTrip.toString(), sendInfo);
//		//i.putExtra(Constants.mainUIRequestedFrom, Constants.mainUIFromCreateTrip);
//		//i.putExtra("MapXML", xmlResponse);//mainUIRequestedFrom
//		startActivity(i);

		
		SubmitButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "Attempting to submit form...",
						Toast.LENGTH_SHORT).show();
				if (validateForm()) {
					Log.d("newTrip", "Form Validated.");
					String getRequest = generateGetRequestFromNewForm();
					Log.d("newTrip", getRequest);
					new ServerCommunication().execute(getRequest);
					
					/*
					 * //String xmlResponse = executeGetRequest(getRequest);
					 * Log.d("newTrip", xmlResponse);
					 */

				}

			}
		});

		destination_tv = (TextView) findViewById(R.id.destination_text);
		datepkr_tv = (TextView) findViewById(R.id.trip_date);

		final ImageButton destination_button = (ImageButton) findViewById(R.id.google_maps_destination_button);

		destination_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Toast.makeText(getApplicationContext(),
						"Let's call the map event.", Toast.LENGTH_LONG).show();

				Log.d("maps", "Intent abt to start ");
				Intent i = new Intent(getApplicationContext(),SetDestinationMapActivity.class);
				
				startActivityForResult(i, SetDestinationMapActivity.DEST_FINAL);
				// destination_tv.setText("Here.");
				/*
				 * Bundle mapinfo = i.getExtras(); double[] latlong = new
				 * double[2]; latlong = mapinfo.getDoubleArray("Lat_Long");
				 * destination .setText("Location:"+latlong[0]+","+latlong[1]);
				 */
			}
		});
		
		destination_tv.setOnTouchListener(new OnTouchListener() {

		    @Override
		    public boolean onTouch(View v, MotionEvent event) {
		        if (event.getAction() == MotionEvent.ACTION_UP) {
		            // do something here when the element is clicked
		        	destination_button.performClick();
		        }

		        // true if the event was handled
		        // and should not be given further down to other views.
		        // if no other child view of this should get the event then return false

		        return true;
		    }
		});
		

		datepkr_tv.setOnTouchListener(new OnTouchListener() {

		    @Override
		    public boolean onTouch(View v, MotionEvent event) {
		        if (event.getAction() == MotionEvent.ACTION_UP) {
		            // do something here when the element is clicked
					showDatePickerDialog(v);
		        }

		        // true if the event was handled
		        // and should not be given further down to other views.
		        // if no other child view of this should get the event then return false

		        return true;
		    }
		});
		
	}

	public void showDatePickerDialog(View v) {
		// new Constants();
		DatePickerFragment newFragment = new DatePickerFragment(datepkr_tv, dateString);
		newFragment.show(getFragmentManager(), "datePicker");
		//this.dateString = newFragment.getDate();
		
		Log.d("ui", "date --> "+dateString);
	}

	public String generateGetRequestFromNewForm() {

		String tripName = name_tv.getText().toString();// name_tv;
		String tripPass = password_tv.getText().toString();// password_tv;
		
		SharedPreferences settings = getSharedPreferences("HANDLE",0);
		String handle = settings.getString("handle", "default_user");			

		// String destination = destination_tv.getText().toString();
		//String destination = "MyFavDestination";// destination_tv.getText().toString().replace()
		String addrLines[] =  destination_tv.getText().toString().split(",");
		
		//String destination = destination_tv.getText().toString().replace(" ","_").replace(",", "__");
		String destination = addrLines[0].replace(" ","_").replace(",", "__");
		
		//String destination = lat.toString()+","+lon.toString();// destination_tv.getText().toString().replace()
		// String date = datepkr_tv.toString();
		dateString = datepkr_tv.getText().toString();

		String getRequestURL = Constants.ChalTrojanHostName;
		getRequestURL += "/ChalTrojan2/CreateTrip?handle=" + handle;
		getRequestURL += "&tripName=" + tripName;
		getRequestURL += "&pwd=" + tripPass + "&destName=" + destination;
		getRequestURL += "&destLang=" + lat + "&destLongi=" + lon;
		if (dateString.equals("") ) {
			dateString = "2012-12-12";
		}
		//getRequestURL += "&tripDate=2012-11-11&active=Y";
		getRequestURL += "&tripDate="+dateString+"&active=Y";

		return getRequestURL;
	}

	public boolean validateForm() {
		name_tv = (TextView) findViewById(R.id.trip_name);
		password_tv = (TextView) findViewById(R.id.trip_password);

		String name_text = name_tv.getText().toString();
		if (name_text.equals("")) {
			name_tv.setError("Please name your trip");
			return false;
		}

		String pass = password_tv.getText().toString();
		if (TextUtils.isEmpty(pass) || pass.length() < 4) {
			password_tv.setError("You must have 4 characters in your password");
			return false;
		}
		
		String dest = destination_tv.getText().toString();
		if (TextUtils.isEmpty(dest) || lat == null || lon == null) {
			destination_tv.setError("Please set a destination");
			return false;
		}		
		
		String date = datepkr_tv.getText().toString();
		Log.d("create", "datepkr_tv --> "+date);
		if (TextUtils.isEmpty(date) || date == null || date.equals("") ) {
			datepkr_tv.setError("Please set a date");
			return false;
		}			
		

		return true;

	}

	public String executeGetRequest(String getURL) {
		Log.d("newTrip", "Inside submit form.");
		String responseStr = "";
		// https://play.google.com/store/devices/details?id=nexus_4_8gb&feature=microsite&hl=en
		HttpClient httpClient = new DefaultHttpClient();
		// String url = "";
		HttpGet httpGet = new HttpGet(getURL);
		try {
			HttpResponse response = httpClient.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				entity.writeTo(out);
				out.close();
				responseStr = out.toString();
				// do something with response
			} else {
				responseStr = "Could not connect.";
			}
		} catch (ClientProtocolException e) {
			// handle exception
		} catch (IOException e) {
			// handle exception
		}

		Log.d("newTrip", responseStr);
		return responseStr;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		try {
			if (requestCode == SetDestinationMapActivity.DEST_FINAL) {
				if (resultCode == SetDestinationMapActivity.DEST_FINAL) {
					Bundle extras = data.getExtras();			
					ll = extras.getDoubleArray(Constants.Lat_Lng);

					lat = ll[0] ;
					lon = ll[1] ;
					Log.d("maps","Lat = "+lat+" & Lngi = "+lon);

					// if (resultCode == SetDestinationMapActivity.DEST_FINAL &&
					// requestCode == SetDestinationMapActivity.DEST_FINAL) {
					// Toast.makeText(getBaseContext(),
					// "You'll be going to "+lat.toString()+"N "+lon.toString()
					// +" W", Toast.LENGTH_LONG).show();
					// }

					String addr = extras.getString(Constants.AddrSting);

					destination_tv.setText(addr);
				}
				if (resultCode == RESULT_CANCELED) {

					// Write your code on no result return

				}
			}
			
		} catch (Exception e){
			
			//do nothing
		}
	
	}// onAcrivityResult

	public void goToMainUI() {
		// TODO Auto-generated method stub

		Intent i = new Intent(getApplicationContext(), MainUIMapActivity.class);
		Bundle sendInfo = new Bundle();
		sendInfo.putInt(Constants.mainUIRequestedFrom, Constants.mainUIFromCreateTrip);	
		sendInfo.putString(Constants.TripName,name_tv.getText().toString().trim());
		if (lat == null || lon == null) {
			sendInfo.putDoubleArray(Constants.Lat_Lng, new double[]{lat, lon});
		} else {
			sendInfo.putDoubleArray(Constants.Lat_Lng, new double[]{lat, lon});
		}
		//i.putExtra(android.content.Intent.extra_  sendInfo);
		
		i.putExtra(Constants.mainUIRequestedFrom, Constants.mainUIFromCreateTrip);
		i.putExtra(Constants.Lat_Lng, new double[]{lat, lon});//mainUIRequestedFrom
		i.putExtra(Constants.TripName,name_tv.getText().toString().trim() );//mainUIRequestedFrom
				
		
		startActivity(i);		
		finish();
		
	}
		
	private class ServerCommunication extends AsyncTask<String,Integer, String> {
		
		public String xmlFromServer;

		@Override
		protected String doInBackground(String... getRequest) {	
			// TODO Auto-generated method stub		
			Log.d("Server", getRequest[0]);
			//String xmlResponse = "";			
			publishProgress(50);			
			
			xmlFromServer= executeGetRequest(getRequest[0]);
			
			publishProgress(100);
			Log.d("Server", xmlFromServer);		
			return xmlFromServer;	
		}		
		

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub			
			super.onPostExecute(result);
			Log.d("ViewTrips",xmlFromServer);
			Toast.makeText(getApplicationContext(), "Got My Trips.",Toast.LENGTH_LONG).show();
			//xmlResponse = xmlFromServer;			
			goToMainUI();									
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			setProgress(values[0]);
		}
		
		public String executeGetRequest(String getURL) {
			Log.d("newTrip", "Inside submit form.");
			String responseStr = "";
			// https://play.google.com/store/devices/details?id=nexus_4_8gb&feature=microsite&hl=en
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(getURL);
			try {
				HttpResponse response = httpClient.execute(httpGet);
				StatusLine statusLine = response.getStatusLine();
				if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
					HttpEntity entity = response.getEntity();
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					entity.writeTo(out);
					out.close();
					responseStr = out.toString();
					// do something with response
				} else {
					responseStr = "Could not connect.";
				}
			} catch (ClientProtocolException e) {
				// handle exception
			} catch (IOException e) {
				// handle exception
			}

			Log.d("newTrip", responseStr);
			return responseStr;
		}
		
	 }


}